<template>
  <div class="processManagement">
    <!-- 添加 -->
    <!-- <el-card class="box-card" shadow="hover">
      <el-row>
        <el-button type="info" class="add-invoice" @click="exportAll">导出</el-button>
      </el-row>
    </el-card> -->

    <span class="down-execel">
				<Poptip v-model="showFilter" placement="bottom-end">
					<i class="el-icon-search poptip-condition-add"></i>
					<a href="javascript:;" class='poptip-condition-add'>列表查找</a>
					<div slot="content">
						<Poptip v-model="showFilterCondition" placement="bottom-start" class='poptip-condition'>
							<i class="el-icon-plus"></i>
							<!-- <a href="javascript:;" @click='getAllAgent'>添加过滤条件</a> -->
							<a href="javascript:;">添加过滤条件</a>

							<div slot="content" class="condition-list">
								<ul>
									<li v-for="(item, index) in columns" class='poptip-condition-item' @click="addFilterCondition(item)" :key="index">{{item.label}}</li>
								</ul>
							</div>
						</Poptip>

						<el-form :model="conditionForm" ref="conditionForm" label-width="120px" class="demo-dynamic" @submit.native.prevent>
							<el-form-item
                v-for="(condition, index) in conditionForm.condition"
                :label="condition.label"
                :key="condition.key"
							  :prop="'condition.' + index + '.value'"
                :rules="{
										required: true, message: condition.label + '不能为空', trigger: 'blur'
								}">

								<el-input  size="small" v-model="condition.value" @keyup.enter.native="submitsearch('conditionForm')"></el-input>
								<el-button @click.stop="removeDomain(condition)" size="mini">删除</el-button>
							</el-form-item>
						</el-form>

						<div class="btns">
							<el-button @click="submitsearch('conditionForm')" size="mini">查询</el-button>
							<el-button @click="resetForm('conditionForm')" size="mini">重置</el-button>
						</div>
					</div>
				</Poptip>
			</span>

    <el-table
      id="IMTable"
      :data="tableData"
      border
      style="width: 100%"
      ref='multipleTable'
      v-loading="loading"
      height="88%"
      tooltip-effect="dark"
      @sort-change='tableSortChange'
      @selection-change="handleSelectionChange">
      <!-- <el-table-column show-overflow-tooltip type="selection" width="55"></el-table-column> -->
      <el-table-column show-overflow-tooltip prop="id" label="ID" width="60" align="left">
		  <template slot-scope="scope">{{(scope.$index+1)+(currentPage-1)*tableSize}}</template>
	  </el-table-column>
      <el-table-column show-overflow-tooltip prop="name" label="姓名"  width="100" align="left" sortable='custom'></el-table-column>
      <el-table-column show-overflow-tooltip prop="id_card" label="身份证"  width="180" align="left" sortable='custom'></el-table-column>
      <el-table-column show-overflow-tooltip prop="phone" label="手机号码"  width="180" align="left" sortable='custom'></el-table-column>
      <el-table-column show-overflow-tooltip prop="email" label="邮箱" min-width="220" align="left" sortable='custom'></el-table-column>
      <el-table-column show-overflow-tooltip prop="organization" label="所属单位"  min-width="300" align="left" sortable='custom'></el-table-column>
      <el-table-column show-overflow-tooltip prop="created_at" label="注册时间" width="250" align="left" sortable='custom'>
        <template slot-scope="scope">{{ scope.row.created_at | formatTime }}</template>
      </el-table-column>
      <el-table-column show-overflow-tooltip label="操作" width="100" align="center" fixed="right">
        <template slot-scope="scope">
          <!-- <el-button type="danger" size="small" @click="delUser(scope.row)">删除</el-button> -->
          <el-button type="warning" size="small" @click="editUser(scope.row)">编辑</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      class="pagination"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="pageSizes"
      :page-size="Number(pageSize)"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    ></el-pagination>
    <!-- 修改 -->
    <dialogEdit ref="editDialog" @changeList="search"></dialogEdit>

    <!-- 修改客户信息 -->
    <editUserDialog ref="editUserDialog"  @changeList="search"></editUserDialog>
  </div>
</template>
<script>
import { getLiaison, delUser } from "~/api/user";
import dialogEdit from "~/components/editUser";
import editUserDialog from "./detailPage/editUserDialog"
export default {
  head:{
    title:'用户管理'
  },
  name: "userList",
  data() {
    return {
      loading: false,
      tableData: [],
      checkTable: [],
      tableSize: 10, //一页几条
      currentPage: 1, //目前在第几页
      pageSizes: [25, 50], //一页可以几条
      total:0,
      showFilter: false, // 控制显示筛选条件
      showFilterCondition: false,
      conditionForm: {
        condition: []
      }, //筛选条件
      columns: [{
          label: '姓名',
          id: 1,
          parameter: 'name'
        },
        {
          label: '手机号',
          id: 2,
          parameter: 'phone'
        },
        {
          label: '身份证号',
          id: 3,
          parameter: 'id_card'
        },
        {
          label: '所属单位',
          id: 4,
          parameter: 'organization'
        },
      ],
      paramsByUser:{
      }
    };
  },
  components: {
    dialogEdit,
    editUserDialog
  },
  async asyncData({ $axios }) {
    //   5 == 用户
    let res = await getLiaison($axios)
    let obj = {
      loading: false
    };
    if (res.data.code == 200) {
		obj.total = res.data.page.total;
		obj.tableData = res.data.data;
      obj.pageSize = res.data.page.per_page;
      obj.tableSize = res.data.page.per_page;
      obj.tableEnd = res.data.page.per_page;
    }
    return obj;
  },
  methods: {
    //编辑
    editInvoices(val) {
      this.$refs.editDialog.showDialog("5", val.id);
    },
    // 删除
    delUser(val) {
      this.$confirm("是否删除用户?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        center: true,
        type: "warning"
      })
        .then(() => {
          delUser(this.$axios, val.id)
            .then(res => {
              if (res.data.code == 200) {
                this.$message({
                  message: "删除成功",
                  type: "success"
                })
                //刷新数据
                this.changeData()
              }
            })
            .catch(err => {
              console.log(err)
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },

    //刷新数据
    onChangeList() {
      this.changeData()
    },
    //获取新数据
    changeData() {
      getLiaison(this.$axios)
        .then(res => {
          this.tableData.splice(0, this.tableData.length, ...res.data.data);
          this.total = res.data.page.total
          this.pageSize = res.data.page.per_page;
          this.tableSize = res.data.page.per_page;
          this.tableEnd = res.data.page.per_page;
        })
        .catch(err => {
          console.log(err);
        });
    },

    // 多选
    handleSelectionChange(val) {
      this.checkTable = val;
    },
    //批量导出
    exportAll() {},

    //选择一页几条
    handleSizeChange(size) {
      this.paramsByUser.perPage = size
      this.paramsByUser.page = 1
      getLiaison(this.$axios, this.paramsByUser)
      .then(res => {
        if (res.data.code == 200) {
          this.tableData = res.data.data;
          this.total = res.data.page.total
          this.pageSize = res.data.page.per_page
          this.tableSize = res.data.page.per_page
          this.tableEnd = res.data.page.per_page
        }
      })

    },
    //选择第几页
    handleCurrentChange(currentPage) {
      this.currentPage = currentPage;
      let params = this.paramsByUser
      params.page = currentPage
      getLiaison(this.$axios, params)
        .then(res => {
          if (res.data.code == 200) {
            this.total = res.data.page.total
            this.tableData = res.data.data
            this.pageSize = res.data.page.per_page
            this.tableSize = res.data.page.per_page
            this.tableEnd = res.data.page.per_page
          }
        })
    },
    async search() {
      this.currentPage = 1
      for (var i = 0; i < this.conditionForm.condition.length; i++) {
        let a = this.conditionForm.condition[i].parameter
        this.paramsByUser[a] = this.conditionForm.condition[i].value
      }

      // 处理分页数据
			delete this.paramsByUser.page

      // 处理排序状态
      delete this.paramsByUser.sort_str
      delete this.paramsByUser.sort_order
      this.$refs['multipleTable'].clearSort()
      this.loading = true
      this.$axios.get('api/liaison', {
        params: this.paramsByUser
      })
      .then( res => {
        if (res.data.code == '200') {
          this.loading = false
          this.tableData = res.data.data
          this.total = res.data.page.total
          this.pageSize = res.data.page.per_page
          this.tableSize = res.data.page.per_page
          this.tableEnd = res.data.page.per_page
          this.showFilter = false
        } else {
          this.$message.error('服务器繁忙')
        }
      })
    },

    // 添加条件筛选
    addFilterCondition(item) {
      let filterItem = {
        value: '',
        label: item.label,
        parameter: item.parameter,
        key: Date.now()
      }

      if (this.conditionForm.condition.length > 0) {
        let conditionlabels = []
        for (let i = 0; i < this.conditionForm.condition.length; i++) {
          conditionlabels.push(this.conditionForm.condition[i].label)
        }
        let Check = conditionlabels.indexOf(item.label)
        Check == -1 ? this.conditionForm.condition.push(filterItem) : this.$message.error('请勿重复添加')
      } else {
        this.conditionForm.condition.push(filterItem)
      }

      this.showFilterCondition = false;
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
      this.$refs['multipleTable'].clearSort()
      this.conditionForm.condition.forEach(v => {
        if (v.value) {
          v.value = null
        }
      });
      this.showFilterCondition = false
      this.paramsByUser = {}
      this.$nextTick(() => {
        this.$refs[formName].clearValidate()
      })
      // this.onChangeList()
      // this.showFilter = false
    },
    submitsearch(formName) {
      let that = this
      this.$refs[formName].validate((valid, prop) => {
        // this.$refs[formName].clearValidate();
        let props = []
        for (let k in prop) {
          props.push(prop[k][0].field)
        }
        if (props.length) {
          that.$refs[formName].validateField(props, (valid2) => {
            if (valid2) {
              return false;
            } else {
              that.search()
            }

          })
        } else {
          that.search()
        }
      })
    },
    removeDomain(item) {
      this.showFilter = true
      delete this.paramsByUser[item.parameter]
      let index = this.conditionForm.condition.indexOf(item)
      if (index !== -1) {
        this.conditionForm.condition.splice(index, 1)
      }
      this.search()
    },
    tableSortChange(column) {
      if (column.order === 'descending') {
        this.paramsByUser.sort_str = column.prop
        this.paramsByUser.sort_order = 'desc'
      } else if (column.order === 'ascending'){
        this.paramsByUser.sort_str = column.prop
        this.paramsByUser.sort_order = 'asc'
      } else {
        delete this.paramsByUser.sort_str
        delete this.paramsByUser.sort_order
      }
      this.loading = true;
      this.$axios.get('api/liaison', {
        params: this.paramsByUser
      })
      .then(res => {
        if (res.data.code == '200') {
          this.loading = false;
          this.tableData = res.data.data
          this.total = res.data.page.total
          this.pageSize = res.data.page.per_page;
          this.tableSize = res.data.page.per_page
          this.tableEnd = res.data.page.per_page;
        } else {
          this.$message.error('服务器繁忙')
        }
      })
    },
    editUser (data) {
      this.$refs.editUserDialog.show(data);
    }
  }
};
</script>
<style lang='less' scoped>
  .processManagement {
    height: 100%; //撑满表格
    .el-table {
      width: 99.9% !important;
    }
  }
  .el-main .ivu-poptip .ivu-poptip-popper .ivu-poptip-content .ivu-poptip-inner {
		min-width: 450px;
		// height: 300px;
		overflow-y: scroll;
	}

	.el-main .poptip-condition .ivu-poptip-popper .ivu-poptip-content .ivu-poptip-inner {
		min-width: 180px;
	}

	.demo-dynamic {
		padding-left: 10px;

		.el-form-item {
			margin-bottom: 12px;
		}

		.el-input {
			width: 240px;
		}

		.el-date-editor {
			width: 240px;
		}

		.el-button {
			padding: 9px 15px;
			vertical-align: baseline;
		}

		.el-form-item__error {
			padding-top: 0;
		}
	}

	.poptip-condition {
		display: block;
		margin-top: 10px;

		.poptip-condition-item {
			line-height: 25px;
			cursor: pointer;
		}

		.poptip-condition-add {
			font-size: 14px;
		}
	}

	.btns {
		margin-top: 10px;
	}

</style>
